package com.example.dao.impl;

import com.example.dao.AnnounceDao;
import com.example.pojo.Announce;
import com.example.utils.DBConnection;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository("announceDao")
public class AnnounceDaoImpl implements AnnounceDao {
    public List<Announce> getAnnounceList() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Announce> announceList = new ArrayList<>();
        try {
            conn = DBConnection.getConnection();
            String sql = "select an_id anId,a_id aId,avatar,title,content,likes,read_times readTimes,publish_time " +
                    "publishTime" +
                    " from " +
                    "announce order by publish_time desc limit 5";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()) {
                Integer anId = rs.getInt("anId");
                Integer aId = rs.getInt("aId");
                String avatar = rs.getString("avatar");
                String title = rs.getString("title");
                String content = rs.getString("content");
                Integer likes = rs.getInt("likes");
                Integer readTimes = rs.getInt("readTimes");
                String publishTime = rs.getString("publishTime").substring(0,16);
                Announce announce = new Announce(anId,aId,avatar,title,content,likes,readTimes,publishTime);
                announceList.add(announce);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DBConnection.close(rs,ps,conn);
        return announceList;
    }
}
